(function() {
	
	var index = 1;
	var size = null;
	var imageIndexIdNum = 0;
	var state = app.getState();
	var memberToken = state.memberToken;
	var childid = state.childid
	var feedback = {
		msgcontent: document.getElementById('msgcontent'),
		msgtype: document.getElementById('msgtype'),
		imageList: document.getElementById('image-list'),
		sendMsgBtn: document.getElementById('sendMsgBtn'),
		sendtype: document.getElementById('sendtype'),
		privatea:document.getElementById('privatea'),
		memberToken:memberToken,
		childid:childid
	};
	
	var url = Apiurl+'index/noticeadd';
	feedback.files = [];
	feedback.uploader = null;
	feedback.deviceInfo = null;
	mui.plusReady(function() {
		//设备信息，无需修改
		feedback.deviceInfo = {
			appid: plus.runtime.appid,
			imei: plus.device.imei, //设备标识
			images: feedback.files, //图片文件
			p: mui.os.android ? 'a' : 'i', //平台类型，i表示iOS平台，a表示Android平台。
			md: plus.device.model, //设备型号
			app_version: plus.runtime.version,
			plus_version: plus.runtime.innerVersion, //基座版本号
			os: mui.os.version,
			net: '' + plus.networkinfo.getCurrentType()
		}
	});
	/**
	 *提交成功之后，恢复表单项 
	 */
	feedback.clearForm = function() {
		feedback.msgcontent.value = '';
		feedback.msgtype.value = '';
		feedback.sendtype.value = '';
		feedback.imageList.innerHTML = '';
		feedback.newPlaceholder();
		feedback.files = [];
		index = 1;
		size = 0;
		imageIndexIdNum = 0;
		feedback.newPlaceholder();
	};
	//返回数组
	feedback.getFileInputArray = function() {
		return [].slice.call(feedback.imageList.querySelectorAll('.file'));
	};
	feedback.addFile = function(path) { 
		//console.log(path);
		feedback.files.push({
			name: "images" + index,
			path: path,
			id: "img-" + index
		});
		index++;
	}; 
	/**
	 * 初始化图片域占位
	 */
	feedback.newPlaceholder = function() {
		var fileInputArray = feedback.getFileInputArray();
		if(fileInputArray &&
			fileInputArray.length > 0 &&
			fileInputArray[fileInputArray.length - 1].parentNode.classList.contains('space')) {
			return;
		};
		if(imageIndexIdNum == 9) {
			return;
		}
		imageIndexIdNum++;

		var placeholder = document.createElement('div') ;
		placeholder.setAttribute('class', 'image-item space');
		//加号和框
		var up = document.createElement("div");
		up.setAttribute('class', 'image-up')
		//增加小X图标
		var closeButton = document.createElement('div');
		closeButton.setAttribute('class', 'image-close');
		closeButton.innerHTML = 'X';
		closeButton.id = "img-" + index;  
		closeButton.addEventListener('tap', function(event) {
			setTimeout(function() {
				for(var temp = 0; temp < feedback.files.length; temp++) {
					if(feedback.files[temp].id == closeButton.id) {
						feedback.files.splice(temp, 1);
					}
				}
				feedback.imageList.removeChild(placeholder);
				imageIndexIdNum--;
				if(imageIndexIdNum == 8) {
					feedback.newPlaceholder();
				}
			}, 0);
			return false;
		}, false);

		var fileInput = document.createElement('div');
		fileInput.setAttribute('class', 'file');
		fileInput.setAttribute('id', 'image-' + imageIndexIdNum);
		fileInput.addEventListener('tap', function(event) {
			var index = (this.id).substr(-1);
			//console.log(this.id);
			if(!this.parentNode.classList.contains('space')) { //该图片位已有图片   返回
				return;
			}

			var btnArray = [{
				title: "拍照"
			}, {
				title: "从相册选取"
			}];
			var fileInputArray = feedback.getFileInputArray();
			plus.nativeUI.actionSheet({
				title: "选择类型",
				cancel: "取消",
				buttons: btnArray
			}, function(actionindex) {
				var actionindex = actionindex.index;
				var text = "你刚点击了\"";
				switch(actionindex) {
					case 0:
						text += "取消";
						break;
					case 1:
						//照相
						var cmr = plus.camera.getCamera();
						var res = cmr.supportedImageResolutions[0];
						var fmt = cmr.supportedImageFormats[0];
						cmr.captureImage(function(e) {
							plus.io.resolveLocalFileSystemURL(e, function(path) {
								var s = path.toLocalURL();
								var name = s.substr(s.lastIndexOf('/') + 1);
								plus.zip.compressImage({
									src: s,
									dst: '_doc/' + name,
									overwrite: true,
									format: "jpg",
									width: "640px",
									height: "auto",
									quality: 30
								}, function(zip) {
									feedback.addFile(zip.target);
									placeholder.classList.remove('space');
									up.classList.remove('image-up');
									feedback.newPlaceholder();
									placeholder.style.backgroundImage = 'url(' + zip.target + ')';
								}, function(zipe) {
									mui.toast('上传失败！')
								});
							}, function(error) {
								console.log("读取拍照文件错误：" + error.message);
							});
						}, function(s) {
							console.log("error" + s);
						}, {
							filename: "_doc/camera/",
							resolution: res,
							format: fmt
						});
						break;
					case 2:
						//相册
						plus.gallery.pick(function(e) {
							var nwaiting = plus.nativeUI.showWaiting();
							var count = 0;
							for(var i in e.files) {
								var name = e.files[i].substr(e.files[i].lastIndexOf('/') + 1);
								console.log(e.files[i]); 
								//console.log("imageIndexIdNum:"+imageIndexIdNum);
								plus.zip.compressImage({
									src: e.files[i],
									dst: '_doc/' + name,
									overwrite: true,
									format: "jpg",
									width: "640px",
									height: "auto",
									quality: 30
								}, function(zip) {
									size += zip.size
									//console.log("filesize:"+zip.size+",totalsize:"+size);
									if(size > (10 * 1024 * 1024)) {
										mui.toast('文件超大,请重新选择~');
										return;
									}

									if(imageIndexIdNum < 10) {
										//一次选多个照片   
										if(e.files.length > 1) {
											if(count == 0) { 
												//console.log(1);
												//多选时第一个图，填充placeholder
												feedback.addFile(zip.target);
												placeholder.classList.remove('space');
												up.classList.remove('image-up');
												placeholder.style.backgroundImage = 'url(' + zip.target + ')';
											} else if(count == e.files.length - 1) { 
												//多选时最后一个图，后面加个placeholder
												feedback.addFile(zip.target);
												feedback.newImageholder(zip.target);
												feedback.newPlaceholder();
												nwaiting.close();
											} else {
												//多选时中间N个图，后面加个placeholder
												feedback.addFile(zip.target);
												feedback.newImageholder(zip.target);
											}
										} else {
											//一次选一个照片
											feedback.addFile(zip.target);
											placeholder.classList.remove('space');
											up.classList.remove('image-up');
											feedback.newPlaceholder();
											placeholder.style.backgroundImage = 'url(' + zip.target + ')';
											nwaiting.close();
										}
										count++;
									} else {
										mui.toast('一次最多上传9张图片！');
									}
								}, function(zipe) {
									mui.toast('压缩失败！')
								});
							}

						}, function(error) {
							//mui.toast(error.message);
						}, {
							filter: 'image',
							multiple: true,
							maximum: 10 - imageIndexIdNum,
							system: false,
							onmaxed: function() {
								plus.nativeUI.alert('最多只能选择9张图片');
							}
						});
						break;
					case 3:
						//录像
						var cmr = plus.camera.getCamera();
						//获取相机
						cmr.startVideoCapture(function(p) {
							//录像
							plus.io.resolveLocalFileSystemURL(p, function(entry) {
								//通过URL参数获取目录对象或文件对象 就是获取到录像文件位置    
								var path = entry.toLocalURL();
								console.log(path); //打印文件位置，可以直接用作上传路径
							}, function(e) {
								console.log("读取录像文件错误：" + e.message);
							});

						}, function(e) {
							console.log("失败");
							plus.nativeUI.toast("录像失败！", {
								duration: "long"
							});
						}, {
							filename: "_doc/camera/", //文件保存目录
							index: 2
						});

						break;
				}
			});
		}, false);

		placeholder.appendChild(closeButton);
		placeholder.appendChild(up);
		placeholder.appendChild(fileInput);
		feedback.imageList.appendChild(placeholder);
	};
	feedback.newPlaceholder();

	/**
	 * 添加图片域
	 */
	feedback.newImageholder = function(imgurl) {
		if(imageIndexIdNum == 9) {
			return;
		}
		imageIndexIdNum++;

		var placeholder = document.createElement('div');
		placeholder.setAttribute('class', 'image-item space');

		var up = document.createElement("div");
		up.setAttribute('class', 'image-up')
		//增加小X图标
		var closeButton = document.createElement('div');
		closeButton.setAttribute('class', 'image-close');
		closeButton.innerHTML = 'X';
		//console.log("closeButton id:"+index);
		closeButton.id = "img-" + (index-1);  
		closeButton.addEventListener('tap', function(event) {
			
			setTimeout(function() {  
				for(var temp = 0; temp < feedback.files.length; temp++) {
					//console.log(feedback.files[temp].id+"=="+closeButton.id); 
					
					
				    if(feedback.files[temp].id == closeButton.id) {
						feedback.files.splice(temp, 1);
					}
				    console.log(feedback.files[temp].id+"=="+closeButton.id);  
				} 
				feedback.imageList.removeChild(placeholder);
				imageIndexIdNum--;  
				if(imageIndexIdNum == 8) {
					feedback.newPlaceholder();
				} 
			}, 0);
			return false;
		}, false);

		var fileInput = document.createElement('div');
		fileInput.setAttribute('class', 'file');
		fileInput.setAttribute('id', 'image-' + imageIndexIdNum);

		placeholder.classList.remove('space');
		up.classList.remove('image-up');
		placeholder.style.backgroundImage = 'url(' + imgurl + ')';

		placeholder.appendChild(closeButton);
		placeholder.appendChild(up);
		placeholder.appendChild(fileInput);
		feedback.imageList.appendChild(placeholder);
	};

	
	//仅发布至日记


	feedback.sendMsgBtn.addEventListener('tap', function(event) {
		   
		var pattern = new RegExp("[`~!@#$^&*()=|{}':;'\\[\\].<>/~#￥……&*（）——|{}【】‘；：”“'-+]") 
		if(pattern.test(feedback.msgcontent.value)){
			return mui.toast('不允许输入特殊字符')
		}
		if(feedback.msgcontent.value.length == 0 && feedback.getFileInputArray().length == 1) {
			return mui.toast('请输入内容或上传图片')
		}
		//判断网络连接
		if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
			return mui.toast("连接网络失败，请稍后再试");
		}
		if(feedback.msgcontent.value!=''){
			feedback.sendMsgBtn.disabled='disabled';
			mui.post('http://tongban.weidu168.com/api/filter', {
				name:feedback.msgcontent.value
			}, function(data) { 
			
			if(data.status==200){
				 
				feedback.send(mui.extend({}, feedback.deviceInfo, {
				 		con: feedback.msgcontent.value,
						type: feedback.msgtype.value.toString(),
						uid: state.userid.toString(), 
						images: feedback.files,
						memberToken:feedback.memberToken,
						child_id:feedback.childid.toString()
				 	}))
			}else if(data.status == 404){
				feedback.sendMsgBtn.removeAttribute('disabled');
				return mui.toast("您输入的内容包含敏感词");
			}else if(data.status == 405){ 
				feedback.sendMsgBtn.removeAttribute('disabled')
				return mui.toast("输入异常");
			}
			}, 'json');
		}else{			
			feedback.send(mui.extend({}, feedback.deviceInfo,{
				 		con: feedback.msgcontent.value,
						type: feedback.msgtype.value.toString(),
						uid: state.userid.toString(), 
						images: feedback.files,
						memberToken:feedback.memberToken,
						child_id:feedback.childid.toString()
				 	}))
		}
		
		
	}, false);

	feedback.send = function(content) {
		feedback.sendMsgBtn.disabled='disabled'
		var nwaiting;
		feedback.uploader = plus.uploader.createUpload(url, {
			method: 'POST',
			
		}, function(upload, status) {
			console.log(JSON.stringify(upload));
			console.log(JSON.stringify(status));
			var json=JSON.parse(upload.responseText);  
			
			//上传成功
			if(status == 200) {
				
				var wobj = plus.webview.getWebviewById("momentsrefresh");    
           		wobj.reload(true); 
				/*mui.fire(plus.webview.getWebviewById("momentsrefresh"), "refreshmomentmsg", {
					changeaa: childid 
				});*/
				//mui.fire(plus.webview.getWebviewById("pcenter"), "refreshpoint", {});
				feedback.clearForm();
				plus.webview.currentWebview().close();
				//feedback.sendMsgBtn.removeAttribute('disabled')  
				nwaiting.close();
				
				var toast_txt = "发布成功";
				if(json.point){ 
					toast_txt += ",恭喜您获得"+json.point+"积分";
				}
				mui.toast(toast_txt); 
			} else {
				console.log("upload fail");
			}
		});
		//添加上传数据
		mui.each(content, function(index, element) {
			if(index !== 'images') {
				feedback.uploader.addData(index, element)
			}
		});
		//添加上传文件
		mui.each(feedback.files, function(index, element) {
			var f = feedback.files[index];
			feedback.uploader.addFile(f.path, {
				key: f.name
			});
		});
		//开始上传任务
		feedback.uploader.start();
		nwaiting = plus.nativeUI.showWaiting();
	};
})();
 